//
//  MZProgramViewController.m
//  Mehfile Zainab
//
//  Created by Sitara Badourali on 15/04/12.
//  Copyright 2012 Mehfile Zainab. All rights reserved.
//

#import "MZProgramViewController.h"
//#import "MZProgramDetailViewController.h"
#import "MZProgramDetailDesignedViewController.h"
#import "MZProgram.h"
#import "ProgramXMLParser.h"
#import "FileManager.h"
#import "MZInfosViewController.h"

const double MZProgramCacheInterval = 10.0;

@implementation MZProgramViewController

@synthesize programArray;
@synthesize spinner;
@synthesize alertView;

@synthesize dataPath;
@synthesize urlArray;
@synthesize filePath;
@synthesize fileDate;
@synthesize connection;
@synthesize XMLParsed;
@synthesize alertDisplayed;

#pragma mark -
#pragma mark View lifecycle

/*
- (void)showInfo:(id)sender
{
    NSLog(@"Info button tapped, show modal view");
    MZInfosViewController *mzInfosViewController = [[MZInfosViewController alloc]
                                                              initWithNibName:@"MZInfosViewController" bundle:nil];
    UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:mzInfosViewController];
    mzInfosViewController.title = @"Informations";
    [mzInfosViewController release];
	navController.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
    UIBarButtonItem *barButtonItem = [[UIBarButtonItem alloc]
									  initWithTitle:@"Fermer"
									  style:UIBarButtonItemStyleBordered
									  target:mzInfosViewController
									  action:@selector(GoBack:)];
	mzInfosViewController.navigationItem.leftBarButtonItem = barButtonItem;
    [self.tabBarController presentModalViewController:navController animated:YES];
    [navController release];
    
}
*/

-(IBAction)GoBack:(id)sender
{
	//[self dismissModalViewControllerAnimated:YES];
    [self.navigationController popToRootViewControllerAnimated:YES];
}

- getProgramDistinctDate {
	NSMutableArray *programDistinctDate = [[NSMutableArray alloc] init];
	for (NSUInteger i=0; i<[programArray count]; i++) {
		NSString *currentDate = [[programArray objectAtIndex:i] getProgramDate];
		if (![programDistinctDate containsObject:currentDate]) {
			[programDistinctDate addObject:currentDate];
		}
	}
	return programDistinctDate;
}


- getProgramArrayForDate:(NSString*) mzProgramDate {
	NSMutableArray *programArrayForDate = [[NSMutableArray alloc] init];
	for (NSUInteger i=0; i<[programArray count]; i++) {
		NSString *currentDate = [[programArray objectAtIndex:i] getProgramDate];
		if ([currentDate isEqualToString:mzProgramDate]) {
			[programArrayForDate addObject:[programArray objectAtIndex:i]];
		}
	}
	return programArrayForDate;
}

/*
- (void)initProgramFromPListFile {

	MZProgram *programItem;
	NSMutableDictionary *currentDictionary;
	programArray = [[NSMutableArray alloc] init];
	FileManager *fm = [[FileManager alloc] init];
	
	NSMutableArray *tempArrayOfDictionaries = [[NSMutableArray alloc] initWithContentsOfFile:[fm OpenDataFile:@"Program.plist"]];
	
	for (NSUInteger i=0; i<[tempArrayOfDictionaries count]; i++) {
		currentDictionary = [tempArrayOfDictionaries objectAtIndex:i];
		programItem = [[MZProgram alloc] init];
		programItem.mzProgramDate = [currentDictionary objectForKey:@"pDate"];
		programItem.mzProgramIslamicDate = [currentDictionary objectForKey:@"pIslamicDate"];
		programItem.mzProgramTime = [currentDictionary objectForKey:@"pTime"];
		programItem.mzProgramTitle = [currentDictionary objectForKey:@"pTitle"];
		programItem.mzProgramDescription = [currentDictionary objectForKey:@"pDescription"];
		[programArray addObject:programItem];
		[programItem release];
		[currentDictionary release];
	}
	
}
*/

-(void) startLoading:(id)data  {
	
	//NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
	
	spinner = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
	[spinner setCenter:CGPointMake(140, 100)];
	
	NSString* messageTitleToUser = @"Mehfile Zainab";
	alertView =
    [[UIAlertView alloc]	initWithTitle:messageTitleToUser
                               message:@"Chargement..."
                              delegate:self
                     cancelButtonTitle:nil
                     otherButtonTitles:nil];
	
	[alertView addSubview:spinner];
	[spinner startAnimating];
	[alertView show];
	
	//[pool drain];
	
}

/*
-(void) stopLoading  {
	//if you programmatically want to close the alert view
	[alertView dismissWithClickedButtonIndex:0 animated:YES];
	// stop spinner
	[spinner stopAnimating];
    
    [self.tableView reloadData];
    
}
*/

- (void)initProgramFromCustomXML {
    
    //NSURL *url = [[NSURL alloc] initWithString:@"http://sitara.azad.free.fr/iosmehfile/remotetest/mzupdate.xml"];
    
    //NSLog(@"Parsing remote XML data from : %@", url);
    
    //NSXMLParser *xmlParser = [[NSXMLParser alloc] initWithContentsOfURL:url];
    
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    
    NSXMLParser *xmlParser = [[NSXMLParser alloc] initWithData:
                                [[NSData alloc] initWithContentsOfFile:[FileManager getCachedDataFile]]];
    
    //Initialize the delegate.
    ProgramXMLParser *parser = [[ProgramXMLParser alloc] initXMLParser:self];
    
    //Set delegate
    [xmlParser setDelegate:parser];
    
    //Start parsing the XML file.
    BOOL success = [xmlParser parse];
    
    if(success)
        NSLog(@"No Errors, XML parsing ended");
    else
        NSLog(@"Error when parsing XML file!");

    //[self stopLoading];
    
    [pool drain];
    
}

- (void) initCache
{
    NSLog(@"Prepare to use our own on-disk cache");
    
	/* create path to cache directory inside the application's Documents directory */
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    self.dataPath = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"MZCache"];
    
	NSLog(@"Initializing cache, value of dataPath : %@",self.dataPath);
	
	/* check for existence of cache directory */
	if ([[NSFileManager defaultManager] fileExistsAtPath:dataPath]) {
		return;
	}
    
	/* create a new cache directory */
	if (![[NSFileManager defaultManager] createDirectoryAtPath:dataPath
								   withIntermediateDirectories:NO
													attributes:nil
														 error:&error]) {
		NSLog(@"Error when creating on-disk cache directory : %@",error);
		return;
	}
}

- (void) getFileModificationDate
{
    
    NSLog(@"Check the last modified date of the data to see if we need to load a new version");
    
	/* default date if file doesn't exist (not an error) */
	self.fileDate = [NSDate dateWithTimeIntervalSinceReferenceDate:0];
    
	if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
		/* retrieve file attributes */
		NSDictionary *attributes = [[NSFileManager defaultManager] attributesOfItemAtPath:filePath error:&error];
		if (attributes != nil) {
			self.fileDate = [attributes fileModificationDate];
		}
		else {
            NSLog(@"Error while checking file attribute of : %@ [ %@ ]",filePath,error);
		}
	}
}

-(void)endLoading {
    
    //if (!XMLParsed) {
        
        //XMLParsed = TRUE;
        
        [self initProgramFromCustomXML];
        
        //NSLog(@"********** Sleep : TO BE REMOVED **********");
        //[NSThread sleepForTimeInterval:3];
        
        //if you programmatically want to close the alert view
        //[alertView dismissWithClickedButtonIndex:0 animated:YES];
    
    // According to the mode, we :
    // - either close the loading popup window
    // - or end the refresh during Pull Down
    if (alertDisplayed) {
        [alertView dismissWithClickedButtonIndex:0 animated:YES];
    } else {
        [refresh endRefreshing];
    }
    
        [self.tableView reloadData];
        
        //[self activatePushNotification];
        
    //}
    
}

- (void) loadDataWithURL:(NSURL *)theURL
{
    
    NSLog(@"Load new or existing cached data");
    
	[filePath release]; /* release previous instance */
	NSString *fileName = [[theURL path] lastPathComponent];
	filePath = [[dataPath stringByAppendingPathComponent:fileName] retain];
    NSLog(@"Get the path to the cached data : %@",filePath);
    
    
    [self getFileModificationDate];
    // get the elapsed time since last file update
    NSTimeInterval time = fabs([fileDate timeIntervalSinceNow]);
    if (time > MZProgramCacheInterval) {
    // file doesn't exist or hasn't been updated for at least one day
        self.connection = [[URLCacheConnection alloc] initWithURL:theURL delegate:self];
    }
    else {
        NSLog(@"Previously cached data found in cache and updated in last %f seconds.",MZProgramCacheInterval);
        [self endLoading];
    }
    
    //self.connection = [[URLCacheConnection alloc] initWithURL:theURL delegate:self];
    
}

-(void)doBackgroundWork {
    
    NSLog(@"Background work in progress...");
    
    /* By default, the Cocoa URL loading system uses a small shared memory cache.
	 We don't need this cache, so we set it to zero when the application launches. */
    
    NSLog(@"Turn off the NSURLCache shared cache");
    
    NSURLCache *sharedCache = [[NSURLCache alloc] initWithMemoryCapacity:0
                                                            diskCapacity:0
                                                                diskPath:nil];
    [NSURLCache setSharedURLCache:sharedCache];
    [sharedCache release];
    
	[self initCache];
    
    NSString *path = [[NSBundle mainBundle] pathForResource:@"MZCache" ofType:@"plist"];
    if (path) {
        NSArray *array = [[NSArray alloc] initWithContentsOfFile:path];
        self.urlArray = [NSMutableArray array];
        for (NSString *element in array) {
            [self.urlArray addObject:[NSURL URLWithString:element]];
        }
        [array release];
    }
    NSLog(@"Get the URL information from property list : %@",[self.urlArray objectAtIndex:0]);
    
	[self loadDataWithURL:[urlArray objectAtIndex:0]];
    
    NSLog(@"Background work ended");
    
}

- (void)initProgram {
	
	//[NSThread detachNewThreadSelector:@selector(startLoading:) toTarget:self withObject:nil];
    //[self startLoading:nil];
    
    // We don't display the loading popup window if Pull Down refresh
    if (alertDisplayed) {
        [self startLoading:nil];
    }
    
    //[self initProgramFromCustomXML];
    //[NSThread detachNewThreadSelector:@selector(initProgramFromCustomXML) toTarget:self withObject:nil];
    //[NSThread detachNewThreadSelector:@selector(doBackgroundWork) toTarget:self withObject:nil];
    [self doBackgroundWork];
    
    //[self stopLoading];
    
}

-(void)refreshView {
    refresh.attributedTitle = [[NSAttributedString alloc] initWithString:@"Actualisation en cours..."];
    
    // We set flag to indicate that we trigerred the Pull Down refresh
    alertDisplayed = FALSE;
    // We refresh the data
    [self initProgram];
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"d MMM h:mm a"];
    NSString *lastUpdated = [NSString stringWithFormat:@"Dernière actualisation : %@", [formatter stringFromDate:[NSDate date]]];
    refresh.attributedTitle = [[NSAttributedString alloc] initWithString:lastUpdated];
    //[refresh endRefreshing];
}

- (void)viewDidLoad {
    
    [super viewDidLoad];
    
    NSLog(@"****************** View did load ******************");
    
    [self enablePullDownRefreshToTarget:self action:@selector(refreshView) title:@"Actualiser"];

    // We set flag to indicate that the loading popup window should be displayed
    alertDisplayed = TRUE;
    // We refresh the data
    [self initProgram];
    
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
}



- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    NSLog(@"****************** View will appear ******************");

    /*
    [self initProgram];
    [self.tableView reloadData];
    */
    
}


/*
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
}
*/
/*
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
}
*/
/*
- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
}
*/
/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        //self.title = NSLocalizedString(@"Second", @"Second");
        self.tabBarItem.image = [UIImage imageNamed:@"program_icon"];
    }
    return self;
}

#pragma mark -
#pragma mark Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
    //return <#number of sections#>;
	//NSLog(@"Number of sections : %d",[programArray count]);
	//return [programArray count];
	return [[self getProgramDistinctDate] count];
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.
    //return <#number of rows in section#>;
	//NSLog(@"Number of rows for section %d : %d",section, [[[programArray objectAtIndex:section] objectForKey:pList] count]);
	//return [[[programArray objectAtIndex:section] objectForKey:pList] count];
	return [[self getProgramArrayForDate:[[self getProgramDistinctDate] objectAtIndex:section]] count];
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
	//return [[programArray objectAtIndex:section] objectForKey:pDate];
	return [[self getProgramDistinctDate] objectAtIndex:section];
}

// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *CellIdentifier = @"Cell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        //cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
		cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue2 reuseIdentifier:CellIdentifier] autorelease];
    }
    
    // Configure the cell...
	NSString *currentDate = [[self getProgramDistinctDate] objectAtIndex:indexPath.section];
	MZProgram *currentProgram = [[self getProgramArrayForDate:currentDate] objectAtIndex:indexPath.row];
    //NSString *textLabel = [[[[programArray objectAtIndex:indexPath.section] objectForKey:pList] objectAtIndex:indexPath.row] objectForKey:pStartDate]; 
	NSString *textLabel = [currentProgram getProgramStartTime];
    //NSString *detailedTextLabel = [[[[programArray objectAtIndex:indexPath.section] objectForKey:pList] objectAtIndex:indexPath.row] objectForKey:pTitle];
	NSString *detailedTextLabel = [currentProgram getProgramTitle]; 
	
	cell.accessoryType = UITableViewCellAccessoryDetailDisclosureButton;
	
	[cell.textLabel setText:textLabel];
	[cell.detailTextLabel setText:detailedTextLabel];
	
    return cell;
}


/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/


/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/


/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/


/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/


#pragma mark -
#pragma mark Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
	[tableView deselectRowAtIndexPath:indexPath animated:YES];
    // Navigation logic may go here. Create and push another view controller.
	/*
	 <#DetailViewController#> *detailViewController = [[<#DetailViewController#> alloc] initWithNibName:@"<#Nib name#>" bundle:nil];
     // ...
     // Pass the selected object to the new view controller.
	 [self.navigationController pushViewController:detailViewController animated:YES];
	 [detailViewController release];
	 */
	
	
	
	MZProgramDetailDesignedViewController *detailViewController = [[MZProgramDetailDesignedViewController alloc] initWithNibName:@"MZProgramDetailDesignedViewController" bundle:nil];
	detailViewController.title = @"Mehfile Zainab";
	//detailViewController.programDict = [programArray objectAtIndex:indexPath.section];
	//detailViewController.pDetailIndex = indexPath.row;
	detailViewController.programItem = [[self getProgramArrayForDate:[[self getProgramDistinctDate] objectAtIndex:indexPath.section]] objectAtIndex:indexPath.row];
    
    UIBarButtonItem *barButtonItem = [[UIBarButtonItem alloc]
                                      initWithTitle:@"Accueil"
                                      style:UIBarButtonItemStyleBordered
                                      target:self
                                      action:@selector(GoBack:)];
    detailViewController.navigationItem.rightBarButtonItem = barButtonItem;
    
	[self.navigationController pushViewController:detailViewController animated:YES];
	[detailViewController release];
	
}

- (void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *) indexPath {
    
	MZProgramDetailDesignedViewController *detailViewController = [[MZProgramDetailDesignedViewController alloc] initWithNibName:@"MZProgramDetailDesignedViewController" bundle:nil];
	detailViewController.title = @"Mehfile Zainab";
	//detailViewController.programDict = [programArray objectAtIndex:indexPath.section];
	//detailViewController.pDetailIndex = indexPath.row;
	detailViewController.programItem = [[self getProgramArrayForDate:[[self getProgramDistinctDate] objectAtIndex:indexPath.section]] objectAtIndex:indexPath.row];
    
    UIBarButtonItem *barButtonItem = [[UIBarButtonItem alloc]
                                      initWithTitle:@"Accueil"
                                      style:UIBarButtonItemStyleBordered
                                      target:self
                                      action:@selector(GoBack:)];
    detailViewController.navigationItem.rightBarButtonItem = barButtonItem;
    
	[self.navigationController pushViewController:detailViewController animated:YES];
	[detailViewController release];
	
}

#pragma mark -
#pragma mark Memory management

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Relinquish ownership any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
    // Relinquish ownership of anything that can be recreated in viewDidLoad or on demand.
    // For example: self.myOutlet = nil;
}


- (void)dealloc {
	[programArray release];
    [super dealloc];
}


/*
 ------------------------------------------------------------------------
 URLCacheConnectionDelegate protocol methods
 ------------------------------------------------------------------------
 */

#pragma mark -
#pragma mark URLCacheConnectionDelegate methods

- (void) connectionDidFail:(URLCacheConnection *)theConnection
{
    NSLog(@"Connection failed!");
    [self endLoading];
    
    UIAlertView* errorAlertView = [[UIAlertView alloc] initWithTitle:@"Mehfile Zainab" message:@"Connexion impossible, merci de réessayer plus tard." delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
    [errorAlertView show];
    
}


- (void) connectionDidFinish:(URLCacheConnection *)theConnection
{
    
    NSLog(@"Connection finished");
    
	if ([[NSFileManager defaultManager] fileExistsAtPath:filePath] == YES) {
        
        // apply the modified date policy
        [self getFileModificationDate];
        NSComparisonResult result = [theConnection.lastModified compare:fileDate];
        if (result == NSOrderedDescending) {
            // file is outdated, so remove it
            if (![[NSFileManager defaultManager] removeItemAtPath:filePath error:&error]) {
                NSLog(@"Error while removing item at path : %@ [ %@ ]",filePath,error);
            }
        }
        
        /*
        NSLog(@"Application launch, clear cache because connection was successful");
        
        for (NSString *file in [[NSFileManager defaultManager] contentsOfDirectoryAtPath:self.dataPath error:&error]) {
            NSString *fileToDelete = [[self.dataPath stringByAppendingPathComponent:file] retain];
            NSLog(@"Delete file : %@",fileToDelete);
            BOOL success = [[NSFileManager defaultManager] removeItemAtPath:fileToDelete error:&error];
            if (!success || error) {
                NSLog(@"Error when deleting data : %@",fileToDelete);
            }
        }
        */
        
	}
    
	if ([[NSFileManager defaultManager] fileExistsAtPath:filePath] == NO) {
		/* file doesn't exist, so create it */
		[[NSFileManager defaultManager] createFileAtPath:filePath
												contents:theConnection.receivedData
											  attributes:nil];
        
		NSLog(@"Newly cached data because data not found in cache or new data available : %@",filePath);
	}
	else {
		NSLog(@"Cached data is up to date,no new data available : %@",filePath);
	}
    
	/* reset the file's modification date to indicate that the URL has been checked */
    
	NSDictionary *dict = [[NSDictionary alloc] initWithObjectsAndKeys:[NSDate date], NSFileModificationDate, nil];
	if (![[NSFileManager defaultManager] setAttributes:dict ofItemAtPath:filePath error:&error]) {
		NSLog(@"Error while setting file attribute on : %@ [ %@ ]",filePath,error);
	}
	[dict release];
    
    [self endLoading];
    
}

@end

